import { Table, Tag, Typography, Card, Button, Space, Modal, Form, Input, Select, InputNumber, message, Row, Col, Spin, Popconfirm } from '@/utils/antd-imports';
import { EditOutlined, PlusOutlined, DeleteOutlined, ReloadOutlined } from '@/utils/icons';
import React, { useState, useEffect } from 'react';
import { companyApi } from '@/api/companyApi';
import dayjs from 'dayjs';

const { Text } = Typography;
const { Option } = Select;

// 公司状态选项
const COMPANY_STATUS_OPTIONS = [
  { value: 'active', label: '正常', color: 'green' },
  { value: 'cancelled', label: '注销', color: 'red' },
  { value: 'revoked', label: '吊销', color: 'orange' },
  { value: 'suspended', label: '停业', color: 'gray' }
];

const CompanyEntity = () => {
  const [companies, setCompanies] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [currentCompany, setCurrentCompany] = useState(null);
  const [form] = Form.useForm();
  const [searchText, setSearchText] = useState('');
  const [selectedStatus, setSelectedStatus] = useState('');
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });

  // 加载公司列表
  const loadCompanies = async (params = {}) => {
    setLoading(true);
    try {
      const response = await companyApi.getAllCompanies();
      if (response.code === 200) {
        setCompanies(response.data || []);
        setPagination(prev => ({
          ...prev,
          total: response.data?.length || 0
        }));
      }
    } catch (error) {
      message.error('加载公司列表失败');
      console.error('加载公司列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 组件挂载时加载数据
  useEffect(() => {
    loadCompanies();
  }, []);

  // 处理添加/编辑公司
  const handleEdit = (company = null) => {
    setCurrentCompany(company);
    if (company) {
      form.setFieldsValue({
        companyName: company.name,
        companyCode: company.code,
        status: company.status,
        taxRate: company.taxRate ? parseFloat(company.taxRate) : 0
      });
    } else {
      form.resetFields();
    }
    setModalVisible(true);
  };

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      const companyData = {
        name: values.companyName,
        code: values.companyCode,
        status: values.status,
        taxRate: values.taxRate ? values.taxRate.toString() : '0'
      };

      if (currentCompany) {
        // 编辑公司
        const response = await companyApi.updateCompany(currentCompany.id, companyData);
        if (response.code === 200) {
          message.success('公司信息更新成功');
          loadCompanies();
        }
      } else {
        // 添加公司
        const response = await companyApi.createCompany(companyData);
        if (response.code === 200) {
          message.success('公司添加成功');
          loadCompanies();
        }
      }
      
      setModalVisible(false);
      form.resetFields();
    } catch (error) {
      console.error('提交表单失败:', error);
    }
  };

  // 删除公司
  const handleDelete = async (company) => {
    try {
      const response = await companyApi.deleteCompany(company.id);
      if (response.code === 200) {
        message.success('公司删除成功');
        loadCompanies();
      }
    } catch (error) {
      message.error('删除公司失败');
      console.error('删除公司失败:', error);
    }
  };

  // 刷新数据
  const handleRefresh = () => {
    loadCompanies();
  };

  // 表格分页变化
  const handleTableChange = (pagination) => {
    setPagination(pagination);
    loadCompanies({
      page: pagination.current,
      size: pagination.pageSize
    });
  };

  // 搜索
  const handleSearch = () => {
    setPagination(prev => ({ ...prev, current: 1 }));
    loadCompanies({
      page: 1,
      size: pagination.pageSize,
      companyName: searchText,
      status: selectedStatus
    });
  };

  // 重置搜索
  const handleReset = () => {
    setSearchText('');
    setSelectedStatus('');
    setPagination(prev => ({ ...prev, current: 1 }));
    loadCompanies({
      page: 1,
      size: pagination.pageSize
    });
  };

  // 公司表格列定义
  const companyColumns = [
    {
      title: '公司名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      fixed: 'left',
      render: (text) => <Text strong>{text}</Text>
    },
    {
      title: '公司编号',
      dataIndex: 'code',
      key: 'code',
      width: 120
    },
    {
      title: '税率',
      dataIndex: 'taxRate',
      key: 'taxRate',
      width: 100,
      render: (rate) => rate ? `${(parseFloat(rate) * 100).toFixed(1)}%` : '0%'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => {
        const statusOption = COMPANY_STATUS_OPTIONS.find(option => option.value === status);
        return <Tag color={statusOption?.color || 'default'}>{statusOption?.label || status}</Tag>;
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 180,
      render: (time) => time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '-'
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      width: 180,
      render: (time) => time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '-'
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确认删除"
            description={`确定要删除公司"${record.name}"吗？`}
            onConfirm={() => handleDelete(record)}
            okText="确定"
            cancelText="取消"
          >
            <Button 
              type="link" 
              danger 
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <div>
      <Card
        title="公司主体管理"
        extra={
          <Space>
            <Button 
              icon={<ReloadOutlined />}
              onClick={handleRefresh}
              loading={loading}
            >
              刷新
            </Button>
            <Button 
              type="primary" 
              icon={<PlusOutlined />}
              onClick={() => handleEdit()}
            >
              添加公司
            </Button>
          </Space>
        }
      >
        {/* 搜索和筛选 */}
        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={6}>
            <Input
              placeholder="搜索公司名称或编号"
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              onPressEnter={handleSearch}
              allowClear
            />
          </Col>
          <Col span={4}>
            <Select
              placeholder="选择状态"
              value={selectedStatus}
              onChange={setSelectedStatus}
              allowClear
              style={{ width: '100%' }}
            >
              {COMPANY_STATUS_OPTIONS.map(option => (
                <Option key={option.value} value={option.value}>
                  {option.label}
                </Option>
              ))}
            </Select>
          </Col>
          <Col span={4}>
            <Button type="primary" onClick={handleSearch}>
              搜索
            </Button>
          </Col>
          <Col span={4}>
            <Button onClick={handleReset}>
              重置筛选
            </Button>
          </Col>
        </Row>

        {/* 公司表格 */}
        <Spin spinning={loading}>
          <Table
            columns={companyColumns}
            dataSource={companies}
            rowKey="id"
            pagination={{
              ...pagination,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total, range) => 
                `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`
            }}
            onChange={handleTableChange}
            scroll={{ x: 1000 }}
            bordered
            size="middle"
          />
        </Spin>
      </Card>

      {/* 添加/编辑公司对话框 */}
      <Modal
        title={currentCompany ? '编辑公司' : '添加公司'}
        visible={modalVisible}
        onOk={handleSubmit}
        onCancel={() => {
          setModalVisible(false);
          form.resetFields();
        }}
        width={600}
        destroyOnClose
      >
        <Form form={form} layout="vertical">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="公司名称"
                name="companyName"
                rules={[{ required: true, message: '请输入公司名称' }]}
              >
                <Input placeholder="请输入公司名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="公司编号"
                name="companyCode"
                rules={[{ required: true, message: '请输入公司编号' }]}
              >
                <Input placeholder="请输入公司编号" />
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="税率"
                name="taxRate"
                rules={[{ required: true, message: '请输入税率' }]}
              >
                <InputNumber 
                  style={{ width: '100%' }} 
                  min={0}
                  max={1}
                  step={0.01}
                  formatter={value => `${(value * 100).toFixed(1)}%`}
                  parser={value => value.replace('%', '') / 100}
                  placeholder="请输入税率"
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="状态"
                name="status"
                rules={[{ required: true, message: '请选择状态' }]}
              >
                <Select placeholder="请选择状态">
                  {COMPANY_STATUS_OPTIONS.map(option => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </div>
  );
};

export default CompanyEntity;